package cn.usain;

import cn.usain.dao.UserMapper;
import cn.usain.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;
import java.util.Map;

@SpringBootTest
public class Mybatisplusdemo01ApplicationTests02 {

   @Autowired
   private UserMapper userMapper;

    @Test
    public void textFindAll() {
        //在mybatisplus中需要使用querywarrper对象
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        //添加条件  大于gt   小于lt
        //queryWrapper.lt("age",21);
        //模糊查询
        queryWrapper.like("name","小");
        List<User> list = userMapper.selectList(queryWrapper);
        System.out.println(list);
    }

    //lambda表达式的写法
    @Test
    public void textFindOne() {
        //在mybatisplus中需要使用querywarrper对象
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        //添加条件  大于gt   小于lt
        //queryWrapper.lt("age",21);
        //模糊查询
        queryWrapper.like(User::getName,"小");
        List<User> list = userMapper.selectList(queryWrapper);
        System.out.println(list);
    }

    @Test
    public void testIfNull2(){
        int minAge = 10;
        int maxAge = 30;
        String name= "J";
        //期望的sql语句： select  * from  user where  age<30  and name like '%J%'
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();

        queryWrapper.gt(minAge!=0,User::getAge,minAge);

        queryWrapper.lt(maxAge!=0,User::getAge,maxAge);

        queryWrapper.like(name!=null,User::getName,name);

        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println("用户列表："+userList);
    }

//    根据年龄排序降序，取前三位
    @Test
    public void testOrder(){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(User::getAge).last("limit 3");
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println("用户列表："+userList);
    }

     /* 分组统计男女人数*/
    @Test
    public void testGroup(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("gender,count(*)");
        //select方法里面编写的内容和select语句后面的内容是一样  select gender count(*) from user group by gender;
        //分组
        queryWrapper.groupBy("gender");
        //如果查询的结果字段和实体类不对应，我们可以使用
        List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
        System.out.println("集合列表："+ maps);
    }
 }
